<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
          @change="handlePlanChange"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评价科目" prop="subjectId">
        <el-select
          v-model="queryParams.subjectId"
          placeholder="请选择评价科目"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="subject.subjectName"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参评人员" prop="candidateId">
        <el-select
          v-model="queryParams.candidateId"
          placeholder="请选择参评人员"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="candidate in candidateList"
            :key="candidate.id"
            :label="candidate.name"
            :value="candidate.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评分状态" prop="scoreStatus">
        <el-select
          v-model="queryParams.scoreStatus"
          placeholder="请选择评分状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待评分" :value="0" />
          <el-option label="已评分" :value="1" />
          <el-option label="已确认" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:score:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 录入评分
        </el-button>
        <el-button
          type="info"
          plain
          @click="openBatchScore"
          v-hasPermi="['eval:score:create']"
        >
          <Icon icon="ep:edit" class="mr-5px" /> 批量评分
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:score:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划名称" align="center" prop="planName" width="150" />
      <el-table-column label="科目名称" align="center" prop="subjectName" width="120" />
      <el-table-column label="科目代码" align="center" prop="subjectCode" width="120" />
      <el-table-column label="参评人员" align="center" prop="candidateName" width="100" />
      <el-table-column label="身份证号" align="center" prop="candidateIdNumber" width="150" />
      <el-table-column label="考评员" align="center" prop="evaluatorName" width="100" />
      <el-table-column label="理论成绩" align="center" prop="theoryScore" width="80">
        <template #default="scope">
          <span v-if="scope.row.theoryScore != null">{{ scope.row.theoryScore }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="实操成绩" align="center" prop="practiceScore" width="80">
        <template #default="scope">
          <span v-if="scope.row.practiceScore != null">{{ scope.row.practiceScore }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="总分" align="center" prop="totalScore" width="80">
        <template #default="scope">
          <el-tag :type="getScoreTagType(scope.row.totalScore, scope.row.maxScore)">
            {{ scope.row.totalScore || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="满分" align="center" prop="maxScore" width="80" />
      <el-table-column label="得分率" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.totalScore && scope.row.maxScore">
            {{ ((scope.row.totalScore / scope.row.maxScore) * 100).toFixed(1) }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否通过" align="center" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isPassed ? 'success' : 'danger'">
            {{ scope.row.isPassed ? '通过' : '不通过' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评分状态" align="center" prop="scoreStatus" width="100">
        <template #default="scope">
          <el-tag :type="getScoreStatusTagType(scope.row.scoreStatus)">
            {{ getScoreStatusText(scope.row.scoreStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评分备注" align="center" prop="scoreComments" width="150">
        <template #default="scope">
          <span v-if="scope.row.scoreComments" :title="scope.row.scoreComments">
            {{ scope.row.scoreComments.length > 20 ? scope.row.scoreComments.substring(0, 20) + '...' : scope.row.scoreComments }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:score:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:score:update']"
            v-if="scope.row.scoreStatus < 2"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="confirm" v-if="scope.row.scoreStatus === 1">
                  确认评分
                </el-dropdown-item>
                <el-dropdown-item command="print">
                  打印成绩单
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.scoreStatus < 2">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ScoreForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <ScoreDetail ref="detailRef" />
  
  <!-- 批量评分弹窗 -->
  <ScoreBatchForm ref="batchFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import {
  EvalScoreRecordVO,
  EvalScoreRecordPageReqVO,
  getScoreRecordPage,
  getScoreRecord,
  deleteScoreRecord,
  exportScoreRecord
} from '@/api/eval/score'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import { EvalSubjectVO, getSubjectListByPlanId } from '@/api/eval/subject'
import { EvalCandidateInfoVO, getCandidateInfoListByPlanId } from '@/api/eval/candidate/index'
import ScoreForm from './ScoreForm.vue'
import ScoreDetail from './ScoreDetail.vue'
import ScoreBatchForm from './ScoreBatchForm.vue'

/** 评分记录 列表 */
defineOptions({ name: 'EvalScore' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalScoreRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalScoreRecordPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  subjectId: undefined,
  candidateId: undefined,
  scoreStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const subjectList = ref<EvalSubjectVO[]>([]) // 科目列表
const candidateList = ref<EvalCandidateInfoVO[]>([]) // 参评人员列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getScoreRecordPage(queryParams)

    // 映射外键数据
    list.value = data.list.map(item => {
      // 映射计划名称
      const plan = planList.value.find(p => p.id === item.planId)

      // 映射科目信息
      const subject = subjectList.value.find(s => s.id === item.subjectId)

      // 映射候选人信息
      const candidate = candidateList.value.find(c => c.id === item.candidateId)

      // 解析评分详情获取理论和实操成绩
      let theoryScore = null
      let practiceScore = null
      if (item.scoreDetails) {
        try {
          const details = JSON.parse(item.scoreDetails)
          theoryScore = details.theoryScore
          practiceScore = details.practiceScore
        } catch (e) {
          console.warn('解析评分详情失败:', e)
        }
      }

      return {
        ...item,
        planName: plan?.planName || '未知计划',
        subjectName: subject?.subjectName || '未知科目',
        subjectCode: subject?.subjectCode || '',
        candidateName: candidate?.name || '未知考生',
        candidateIdNumber: candidate?.idNumber || '',
        theoryScore,
        practiceScore,
        evaluatorName: '待获取' // TODO: 需要获取考评员信息
      }
    })

    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  subjectList.value = []
  candidateList.value = []
  handleQuery()
}

/** 计划变更处理 */
const handlePlanChange = async (planId: number) => {
  if (planId) {
    // 加载科目列表
    subjectList.value = await getSubjectListByPlanId(planId)
    // 加载参评人员列表
    candidateList.value = await getCandidateInfoListByPlanId(planId)
  } else {
    subjectList.value = []
    candidateList.value = []
  }
  queryParams.subjectId = undefined
  queryParams.candidateId = undefined
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, id?: number) => {
  if (type === 'create') {
    // 创建新评分记录，可以传递预选的基础信息
    const baseData = {
      planId: queryParams.planId,
      subjectId: queryParams.subjectId,
      candidateId: queryParams.candidateId
    }
    formRef.value.open(type, baseData)
  } else {
    // 编辑现有记录，需要先获取记录详情
    if (id) {
      try {
        const data = await getScoreRecord(id)
        formRef.value.open(type, data)
      } catch (error) {
        message.error('获取评分记录失败')
      }
    }
  }
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 批量评分操作 */
const batchFormRef = ref()
const openBatchScore = () => {
  batchFormRef.value.open()
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalScoreRecordVO) => {
  switch (command) {
    case 'confirm':
      await handleConfirmScore(row.id!)
      break
    case 'print':
      handlePrintScore(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 确认评分 */
const handleConfirmScore = async (id: number) => {
  try {
    await message.confirm('确认后将无法修改评分，是否继续？')
    // TODO: 调用确认评分接口
    message.success('评分确认成功')
    await getList()
  } catch {}
}

/** 打印成绩单 */
const handlePrintScore = (id: number) => {
  // TODO: 实现打印功能
  message.info('打印功能开发中...')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteScoreRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportScoreRecord(queryParams)
    download.excel(data, '评分记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分数标签类型 */
const getScoreTagType = (score: number, maxScore: number) => {
  const rate = score / maxScore
  if (rate >= 0.9) return 'success'
  if (rate >= 0.8) return 'primary'
  if (rate >= 0.6) return 'warning'
  return 'danger'
}

/** 获取评分状态标签类型 */
const getScoreStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'primary', 2: 'success' }
  return typeMap[status] || ''
}

/** 获取评分状态文本 */
const getScoreStatusText = (status: number) => {
  const textMap = { 0: '待评分', 1: '已评分', 2: '已确认' }
  return textMap[status] || '未知'
}

/** 根据ID获取候选人姓名 */
const getCandidateName = (candidateId?: number) => {
  if (!candidateId) return ''
  const candidate = candidateList.value.find(c => c.id === candidateId)
  return candidate?.name || ''
}

/** 根据ID获取科目名称 */
const getSubjectName = (subjectId?: number) => {
  if (!subjectId) return ''
  const subject = subjectList.value.find(s => s.id === subjectId)
  return subject?.subjectName || ''
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取审核通过的计划（已审批、已发布、进行中）
    const approvedPlans = await getPlanListByStatus(2) // 已审批
    const publishedPlans = await getPlanListByStatus(3) // 已发布
    const inProgressPlans = await getPlanListByStatus(4) // 进行中
    planList.value = [...approvedPlans, ...publishedPlans, ...inProgressPlans]
  } catch (error) {
    console.error('加载计划列表失败:', error)
    planList.value = []
  }
}

/** 初始化所有数据 */
const initializeData = async () => {
  await loadPlanList()
  // 如果有默认计划，加载相关数据
  if (planList.value.length > 0) {
    const firstPlan = planList.value[0]
    if (firstPlan.id) {
      try {
        subjectList.value = await getSubjectListByPlanId(firstPlan.id)
        candidateList.value = await getCandidateInfoListByPlanId(firstPlan.id)
      } catch (error) {
        console.error('加载默认计划数据失败:', error)
      }
    }
  }
  getList()
}

/** 初始化 **/
onMounted(() => {
  initializeData()
})
</script>
